package com.robot.service.impl;

import algorithm.AlgorithmCaller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.robot.common.enums.*;
import com.robot.common.result.PageResult;
import com.robot.common.utils.MinioUtils;
import com.robot.dao.cache.ActionUnitTemplateCache;
import com.robot.dao.dto.*;
import com.robot.dao.entity.*;
import com.robot.dao.feigndto.context.RequestContext;
import com.robot.dao.feigndto.robotdto.AgentCreate;
import com.robot.dao.mapper.*;
import com.robot.dao.vo.*;
import com.robot.repository.RobotRepoEntity;
import com.robot.repository.RobotRepository;
import com.robot.service.*;
import com.robot.service.CategoryService;
import com.robot.service.IntegralService;
import com.robot.service.RobotService;
import com.robot.service.UserKnowledgeService;
import com.robot.service.action_unit.ActionUnitImplKnowledge;
import com.robot.service.action_unit.ActionUnitImplBigModel;
import com.robot.service.action_unit.ActionUnitImplWebSearch;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class RobotServiceImpl implements RobotService {
    //文件上传缓冲bucket
    private static final String BUFFER_ID = "1821091408614404171";
    private static final String BUFFER_BUCKET_NAME = "1274682200419205120";


    @Autowired
    private RobotRepository robotRepository;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private KnowledgeMapper knowledgeMapper;

    @Autowired
    private FileMapper fileMapper;

    @Autowired
    private RobotKnowledgeMapper robotKnowledgeMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserKnowledgeService userKnowledgeService;
    @Autowired
    private ActionUnitMapper actionUnitMapper;

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private MinioUtils minioUtils;

    @Autowired
    private AlgorithmCaller algorithmCaller;

    @Autowired
    private IntegralService integralService;
    @Qualifier("robotUserUsetimeMapper")
    @Autowired
    private RobotUserUsetimeMapper robotUserUsetimeMapper;
    @Autowired
    private RobotUserUsetimeService robotUserUsetimeService;

    /**
     * 分页查询机器人列表
     *
     * @param robotPageQueryDTO
     * @return
     */
    public PageResult queryRobotList(RobotPageQueryDTO robotPageQueryDTO) {
        int page = (robotPageQueryDTO.getPage() == 0) ? 1 : robotPageQueryDTO.getPage();
        int pageSize = (robotPageQueryDTO.getPageSize() <= 0) ? 10 : robotPageQueryDTO.getPageSize();

        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Robot> mpPage = new Page<>(page,pageSize);
        IPage<RobotRepoEntity> pageResult = robotRepository.pageQuery(robotPageQueryDTO.getCategoryName(), robotPageQueryDTO.getRobotName(),mpPage);

        List<RobotRepoEntity> robots = pageResult.getRecords();

        List<RobotOverViewVO> robotList = new ArrayList<>();
        for (RobotRepoEntity robot : robots) {
            RobotOverViewVO robotVO = new RobotOverViewVO();
            BeanUtils.copyProperties(robot, robotVO);
            robotVO.setRobotId(String.valueOf(robot.getId()));
            robotVO.setCategory(robot.getCategoryName());
            robotList.add(robotVO);
        }

        boolean hasMore = page < pageResult.getPages();
        return new PageResult(pageResult.getTotal(), hasMore, robotList);
    }

    /**
     * 每天五点定时更新机器人热度星级
     *
     * @return
     */
    public Integer updateRobotHeatStars() {
        List<RobotRepoEntity> allRobots = robotRepository.queryAllRobots();
        List<Integer> robotHeatList = allRobots.stream()
                .map(RobotRepoEntity::getRobotHeat)
                .sorted()
                .collect(Collectors.toList());
        int cnt=0;
        for (RobotRepoEntity toEditRobot : allRobots) {
            Integer listIndex = findListIndex(toEditRobot.getRobotHeat(), robotHeatList);
            if (!listIndex.equals(toEditRobot.getRobotHeatStars())) {
                //更新热度星级
                robotRepository.updateHeatStar(toEditRobot.getId(),listIndex);
                cnt++;
            }
        }
        return cnt;
    }

    /**
     * 新建数据源组件
     *
     * @param fileSetDTO
     * @return
     */
    public FileSetOverViewVO createFileSetActionUnit(FileSetDTO fileSetDTO) {
        Knowledge knowledge = new Knowledge();
        BeanUtils.copyProperties(fileSetDTO, knowledge);
        knowledge.setKnowledgeName(fileSetDTO.getFileSetName());
        knowledge.setApplicationNumber(0);
        knowledge.setFileNumber(0);
        knowledge.setIsDelete(IsDeleteEnum.EXIST.getValue());
        String bucketName = minioUtils.existBucketPartial(String.valueOf(knowledge.getId()));
        knowledge.setMinioBucketName(bucketName);
        knowledgeMapper.create(knowledge);

        Long knowledgeid = knowledge.getId();
        UserKnowledge userKnowledge = new UserKnowledge();
        userKnowledge.setUserId(new Long(fileSetDTO.getUserId()));
        userKnowledge.setKnowledgeId(knowledgeid);
        userKnowledgeService.save(userKnowledge);

        FileSetOverViewVO fileSetOverViewVO = new FileSetOverViewVO();
        fileSetOverViewVO.setFileSetId(String.valueOf(knowledgeid));
        fileSetOverViewVO.setMinioBucketName(bucketName);
        return fileSetOverViewVO;
    }

    @Override
    public void topCategoryName(String categoryName,String companyCode,String userId) {
        List<Long> robotId =robotRepository.queryByCategoryNameLimit(categoryName,companyCode);
        for (Long robotId1 : robotId) {
            robotUserUsetimeService.creatrobotuser(String.valueOf(robotId1),userId);
        }
    }


    //查询在哪个列表里
    public static int findListIndex(int number, List<Integer> lists) {
        int size = lists.size();
        int fortyPercentIndex = (int) (size * 0.4);
        int seventyPercentIndex = (int) (size * 0.7);
        int ninetyPercentIndex = (int) (size * 0.9);
        int ninetyFivePercentIndex = (int) (size * 0.95);

        if (lists.indexOf(number) < fortyPercentIndex) {
            return 1;
        } else if (lists.indexOf(number) < seventyPercentIndex) {
            return 2;
        } else if (lists.indexOf(number) < ninetyPercentIndex) {
            return 3;
        } else if (lists.indexOf(number) < ninetyFivePercentIndex) {
            return 4;
        } else {
            return 5;
        }
    }

    /**
     * 根据用户ID查询机器人列表
     *
     * @param robotPageQueryDTO
     * @return
     */
    public PageResult queryByUserId(RobotPageQueryDTO robotPageQueryDTO) {
        Long userId = Long.valueOf(robotPageQueryDTO.getUserId());
        IPage<Robot> page = robotRepository.queryByUserId(userId);
        List<Robot> robots = page.getRecords();

        //在threadlocal中获得企业ID

        User user = new User();
        user.setId(userId);
        user = userMapper.queryById(user);

        if (robots == null) {
            return null;
        } else {
            List<RobotOverViewVO> robotOverViewVOList = new ArrayList<>();
            for (Robot robot : robots) {
                RobotOverViewVO robot1 = new RobotOverViewVO();
                robot1.setRobotId(String.valueOf(robot.getUserId()));
                robot1.setRobotName(robot.getRobotName());
                robot1.setRobotDescription(robot.getRobotDescription());
                robot1.setRobotUrl(robot.getRobotUrl());

                robot1.setCategory(categoryMapper.queryByIdAndName(user.getCompanyCode(), robot.getCategoryName()).getCategoryName());

                robotOverViewVOList.add(robot1);
            }

            boolean hasMore = false;
            long total = page.getTotal();
            Long totalPages = (long) Math.ceil(total / robotPageQueryDTO.getPageSize());
            if (total % robotPageQueryDTO.getPageSize() > 0) {
                totalPages = totalPages + 1;
            }
            if (totalPages != robotPageQueryDTO.getPage()) {
                hasMore = true;
            }

            return new PageResult(page.getTotal(), hasMore, robotOverViewVOList);
        }
    }

    /**
     * 根据模板创建机器人
     *
     * @param iddto
     * @return
     */
    @Transactional
    public AgentDetailVO createByTemplate(IDDTO iddto) {
        //提取模板机器人ID用户ID
        Long templateRobotId = Long.valueOf(iddto.getRobotId());
        Long userId = Long.valueOf(iddto.getUserId());
        //根据ID查询模板机器人
        RobotRepoEntity templateRobot = robotRepository.queryByRobotId(templateRobotId);

        //新机器人实体
        RobotRepoEntity newRobot = new RobotRepoEntity();
        BeanUtils.copyProperties(templateRobot, newRobot);
        newRobot.setId(null);
        newRobot.setUserId(userId);
        // todo 企业ID默认
//        newRobot.setEnterpriseId(1L);
        newRobot.setRobotName(newRobot.getRobotName() + " - 副本");
        List<Knowledge> knowledges = knowledgeMapper.queryByRobotId(newRobot.getId());

        // 创建新机器人
        RobotRepoEntity resultRobot = createRobotAndKnowledge(newRobot);
        // 创建默认知识库
        Knowledge knowledge = new Knowledge();
        knowledge.setKnowledgeType(KnowledgeTypeEnum.INDIVIDUAL.getCode());
        knowledge.setIsDelete(IsDeleteEnum.EXIST.getValue());
        knowledge.setKnowledgeName(newRobot.getRobotName() + "知识库");
        knowledge.setApplicationNumber(1);
        knowledge.setFileNumber(0);
        String bucketName = minioUtils.createBucket();
        knowledge.setMinioBucketName(bucketName);
        knowledgeMapper.create(knowledge);

        //复制知识库
        for (Knowledge knowledgeToCopy : knowledges) {
            if (knowledgeToCopy.getKnowledgeType() == KnowledgeTypeEnum.ENTERPRISE.getCode()) {
                RobotKnowledge robotKnowledge = new RobotKnowledge();
                robotKnowledge.setRobotId(resultRobot.getId());
                robotKnowledge.setKnowledgeId(knowledgeToCopy.getId());
                robotKnowledgeMapper.create(robotKnowledge);
            }
        }

        return queryRobotDetailByRobot(resultRobot);
    }

    /**
     * 根据机器人ID查询机器人详情
     *
     * @param queryRobotDetailDTO
     * @return
     */
    public AgentDetailVO queryRobotIdByRobotId(QueryRobotDetailDTO queryRobotDetailDTO) {
        RobotRepoEntity robot = robotRepository.queryByRobotId(Long.valueOf(queryRobotDetailDTO.getRobotId()));

        return queryRobotDetailByRobot(robot, queryRobotDetailDTO.getNeedActionUnitList());
    }

    /**
     * 机器人置顶
     *
     * @param iddto
     * @return
     */


    /**
     * 删除机器人，逻辑删除
     *
     * @param iddto
     */
    @Transactional
    public void delete(IDDTO iddto) {


        String category_name = robotRepository.queryByRobotId(Long.valueOf(iddto.getRobotId())).getCategoryName();

        robotRepository.deleteRobot(Long.valueOf(iddto.getRobotId()));

        // todo 企业ID现在为默认值
        if (robotRepository.queryByCategoryName(category_name).isEmpty()) {
            Category category = new Category();
            category = categoryMapper.queryByIdAndName("测试", category_name);
            category.setIsDelete(1);
            categoryService.updateById(category);
        }

        //同步知识库表中的应用数量
        List<Knowledge> knowledges = knowledgeMapper.queryByRobotId(Long.valueOf(iddto.getRobotId()));
        for (Knowledge knowledge : knowledges) {
            knowledge.setApplicationNumber(knowledge.getApplicationNumber() - 1);
            knowledgeMapper.updateById(knowledge);
        }

    }

    /**
     * 修改机器人信息
     *
     * @param agentDTO
     */
    @Transactional
    public void updateRobotDetail(AgentDTO agentDTO) {

        BasicInfoDTO basicInfo = agentDTO.getBasicInfo();
        Long robotId = Long.valueOf(basicInfo.getRobotId());
        List<ActionUnit> actionUnits = actionUnitMapper.selectByRobotId(robotId);
        updateBasicInfo(basicInfo);

        updateDatasource(agentDTO.getDatasourceList(), actionUnits, robotId);

        updateSearching(agentDTO.getWebSearch(), actionUnits, robotId);

        updateBigModel(agentDTO.getBigModel(), actionUnits, robotId);

    }

    private void updateBigModel(BigModelDTO bigModel, List<ActionUnit> actionUnits, Long robotId) {
        //更新大模型组件
        if (bigModel == null || bigModel.getActionUnit() == null) {
            return;
        }
        Long unitId = 0L;
        for (ActionUnit actionUnit : actionUnits) {
            if (actionUnit.getActionUnitType() == 1) {

                unitId = actionUnit.getId();
            }
        }

        //更新大模型相关
        ActionUnit actionUnit = new ActionUnit();
        BeanUtils.copyProperties(bigModel.getActionUnit(), actionUnit);
        actionUnit.setRobotId(robotId);
        actionUnit.setActionUnitType(ActionUnitTypeEnum.BIG_MODEL.getCode());
        actionUnit.setDetail(bigModel.getActionUnit().getDetail().toString());

        if (actionUnit.getId() != null) {
            actionUnit.setId(Long.valueOf(bigModel.getActionUnit().getUnitId()));
            actionUnit.setUpdateTime(LocalDateTime.now());
            actionUnitMapper.update(actionUnit);
        } else {
            if (unitId != 0) {
                ActionUnit deleteActionUnit = new ActionUnit();
                deleteActionUnit.setId(unitId);
                actionUnitMapper.delete(deleteActionUnit);
            }
            actionUnit.setCreateTime(LocalDateTime.now());
            actionUnit.setUpdateTime(LocalDateTime.now());
            actionUnitMapper.create(actionUnit);
        }
    }

    private void createBigModelActionUnit(Long robotID,BigModelDTO bigModel){
        ActionUnit actionUnit = new ActionUnit();
//        BeanUtils.copyProperties(bigModel.getActionUnit(), actionUnit);
        actionUnit.setRobotId(robotID);
        actionUnit.setActionUnitType(ActionUnitTypeEnum.BIG_MODEL.getCode());
        actionUnit.setDetail("");
        actionUnit.setUnitName("大模型");
        actionUnit.setCreateTime(LocalDateTime.now());
        actionUnit.setUpdateTime(LocalDateTime.now());
        // todo 枚举
        actionUnit.setUnitTemplateCode("ai_big_model_text_chat");
        actionUnitMapper.create(actionUnit);
    }

    private void updateSearching(WebSearchDTO webSearch, List<ActionUnit> actionUnits, Long robotId) {
        //有则更新，无则新增
        if (webSearch == null || webSearch.getActionUnit() == null) {
            return;
        }
        webSearch.getIsNeedWebSearch();
        Long unitId = 0L;
        for (ActionUnit actionUnit : actionUnits) {
            if (actionUnit.getActionUnitType() == ActionUnitTypeEnum.SEARCHING.getCode()) {
                //搜索组件只有一个，找到搜索组件的ID
                unitId = actionUnit.getId();
                break;
            }
        }

        //更新大模型相关
        ActionUnit actionUnit = new ActionUnit();
        BeanUtils.copyProperties(webSearch.getActionUnit(), actionUnit);
        actionUnit.setRobotId(robotId);
        actionUnit.setActionUnitType(ActionUnitTypeEnum.SEARCHING.getCode());
        actionUnit.setDetail(webSearch.getActionUnit().getDetail().toString());


        if (webSearch.getActionUnit().getUnitId() != null) {
            //更新现有的
            actionUnit.setId(Long.valueOf(webSearch.getActionUnit().getUnitId()));
            actionUnit.setUpdateTime(LocalDateTime.now());
            actionUnitMapper.update(actionUnit);
        } else {
            if (unitId != 0) {//旧的删除了
                ActionUnit deleteActionUnit = new ActionUnit();
                deleteActionUnit.setId(unitId);
                actionUnitMapper.delete(deleteActionUnit);
            }//新的新增进来
            actionUnit.setCreateTime(LocalDateTime.now());
            actionUnit.setUpdateTime(LocalDateTime.now());
            actionUnitMapper.create(actionUnit);
        }

    }

    private void updateDatasource(List<ActionUnitDTO> datasourceList, List<ActionUnit> actionUnits, Long robotId) {

        if (datasourceList == null || datasourceList.isEmpty()) {
            return;
        }

        Boolean knowledgeNeedUpdate = false;
        Boolean fileSetNeedUpdate = false;

        List<String> stringIDS = new ArrayList<>();
        List<ActionUnitDTO> fileSet = new ArrayList<>();
        List<ActionUnitDTO> knowledgeSet = new ArrayList<>();
        List<ActionUnitDTO> webParserSet = new ArrayList<>();
        for (ActionUnitDTO actionUnitDTO : datasourceList) {
            if (actionUnitDTO.getDetail() != null) {
                JSONObject detailJson = actionUnitDTO.getDetail();
                if (detailJson.containsKey("knowledges")) {
                    //知识库数据源
                    JSONArray array = detailJson.getJSONArray("knowledges");
                    knowledgeSet.add(actionUnitDTO);
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject obj = array.getJSONObject(i);
                        if (obj.containsKey("knowledgeId")) {
                            stringIDS.add(obj.getString("knowledgeId"));
                        }
                    }
                } else if (detailJson.containsKey("fileList")) {
                    //除网页解析外的其他数据源
//                    stringIDS.add(detailJson.getString("fileSetId"));
                    fileSet.add(actionUnitDTO);
                } else {
                    webParserSet.add(actionUnitDTO);
                }
            }
        }

        updateFileSet(fileSet, actionUnits, robotId);

        updateKnowledgeSetActionUnit(knowledgeSet, actionUnits, robotId);

        updateWebParser(webParserSet, actionUnits, robotId);

    }

    private void updateWebParser(List<ActionUnitDTO> webParserSet, List<ActionUnit> actionUnits, Long robotId) {
        //更新网页解析数据源
        List<Long> oldIds = new ArrayList<>();//原本的文件夹列表
        for (ActionUnit actionUnit : actionUnits) {
            if (Objects.equals(actionUnit.getActionUnitType(), ActionUnitTypeEnum.DATA_SOURCE.getCode())) {
                //搜索组件只有一个，找到搜索组件的ID
                if (Objects.equals(actionUnit.getUnitTemplateCode(), "website_url_parser")) {
                    oldIds.add(actionUnit.getId());
                }
            }
        }

        Map<Long, ActionUnit> actionUnitMap = new HashMap<>();//根据ID查出对象，操作对应数据库
        for (ActionUnitDTO actionUnitDTO : webParserSet) {
            ActionUnit actionUnit = new ActionUnit();
            BeanUtils.copyProperties(actionUnitDTO, actionUnit);
            actionUnit.setRobotId(robotId);
            actionUnit.setActionUnitType(ActionUnitTypeEnum.DATA_SOURCE.getCode());
            actionUnit.setDetail(actionUnitDTO.getDetail().toString());
            if (actionUnitDTO.getUnitId() == null) {
                actionUnit.setCreateTime(LocalDateTime.now());
                actionUnit.setUpdateTime(LocalDateTime.now());
                actionUnitMapper.create(actionUnit);
            } else {
                actionUnit.setId(Long.valueOf(actionUnitDTO.getUnitId()));
                actionUnitMap.put(actionUnit.getId(), actionUnit);
            }
        }

        List<String> newFileSet = webParserSet.stream()
                .map(ActionUnitDTO::getUnitId)
                .collect(Collectors.toList());

        List<Long> newIds = newFileSet.stream()
                .map(str -> {
                    try {
                        // 尝试将字符串转换为Long
                        return Long.parseLong(str);
                    } catch (NumberFormatException e) {
                        // 如果转换失败，可以选择返回null或者抛出异常
                        // 这里我们选择返回-null
                        return null;
                    }
                })// 过滤掉null值
                .collect(Collectors.toList());
        List<Long> addFileSet = newIds.stream().filter(item -> !oldIds.contains(item)).collect(Collectors.toList());
        List<Long> removeFileSet = oldIds.stream().filter(item -> !newIds.contains(item)).collect(Collectors.toList());

        for (Long element : oldIds) {
            if (newIds.contains(element)) {
                //已有的更新
                ActionUnit actionUnitNeedUpdate = actionUnitMap.get(element);
                actionUnitNeedUpdate.setUpdateTime(LocalDateTime.now());
                actionUnitMapper.update(actionUnitNeedUpdate);
            }
        }
        //删除组件
        for (Long removeFileSetId : removeFileSet) {
            ActionUnit removeActionUnit = actionUnitMapper.selectById(removeFileSetId);

            actionUnitMapper.delete(removeActionUnit);
        }

    }

    private void updateKnowledgeSetActionUnit(List<ActionUnitDTO> knowledgeSet, List<ActionUnit> actionUnits, Long robotId) {

        Map<Long, ActionUnit> actionUnitMap = new HashMap<>();//根据ID查出对象，操作对应数据库
        List<Long> newActionUnitIds = new ArrayList<>();
        List<Long> newKnowledgeIds = new ArrayList<>();
        List<Long> oldKnowledgeIds = new ArrayList<>();
        List<Long> oldActionUnitIds = new ArrayList<>();
        for (ActionUnitDTO actionUnitDTO : knowledgeSet) {
            ActionUnit actionUnit = new ActionUnit();
            BeanUtils.copyProperties(actionUnitDTO, actionUnit);
            actionUnit.setRobotId(robotId);
            actionUnit.setActionUnitType(ActionUnitTypeEnum.DATA_SOURCE.getCode());
            actionUnit.setDetail(actionUnitDTO.getDetail().toString());
            if (actionUnitDTO.getUnitId() == null) {
                actionUnit.setCreateTime(LocalDateTime.now());
                actionUnit.setUpdateTime(LocalDateTime.now());
                actionUnitMapper.create(actionUnit);
            } else {
                actionUnit.setId(Long.valueOf(actionUnitDTO.getUnitId()));
                newActionUnitIds.add(actionUnit.getId());
            }

        }
        for (ActionUnit actionUnit : actionUnits) {
            if (Objects.equals(actionUnit.getActionUnitType(), ActionUnitTypeEnum.DATA_SOURCE.getCode())) {
                if (Objects.equals(actionUnit.getUnitTemplateCode(), "knowledge")) {
                    //查询数据库中所有知识库组件
                    oldActionUnitIds.add(actionUnit.getId());
                    JSONObject detailJson = JSONObject.parseObject((String) actionUnit.getDetail());
                    JSONArray array = detailJson.getJSONArray("knowledges");
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject obj = array.getJSONObject(i);
                        if (obj.containsKey("knowledgeId")) {
                            oldKnowledgeIds.add(Long.valueOf(obj.getString("knowledgeId")));
                        }
                    }
                    actionUnitMap.put(actionUnit.getId(), actionUnit);
                }
            }
        }
        for (ActionUnitDTO actionUnitDTO : knowledgeSet) {
            if (actionUnitDTO.getDetail() != null) {
                JSONObject detailJson = actionUnitDTO.getDetail();
                if (detailJson.containsKey("knowledges")) {
                    //前端传回的知识库组件
                    JSONArray array = detailJson.getJSONArray("knowledges");
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject obj = array.getJSONObject(i);
                        if (obj.containsKey("knowledgeId")) {
                            newKnowledgeIds.add(Long.valueOf(obj.getString("knowledgeId")));
                        }
                    }
                }
            }
            updateKnowledgeSet(newKnowledgeIds, oldKnowledgeIds, robotId);
        }

        List<Long> addKnowledgeActionUnit = newActionUnitIds.stream().filter(item -> !oldActionUnitIds.contains(item)).collect(Collectors.toList());
        List<Long> removeKnowledgesActionUnit = oldActionUnitIds.stream().filter(item -> !newActionUnitIds.contains(item)).collect(Collectors.toList());

        for (Long element : oldActionUnitIds) {
            if (newActionUnitIds.contains(element)) {
                //已有的更新
                ActionUnit actionUnitNeedUpdate = actionUnitMap.get(element);
                actionUnitNeedUpdate.setUpdateTime(LocalDateTime.now());
                actionUnitMapper.update(actionUnitNeedUpdate);
            }
        }
        for (Long l : removeKnowledgesActionUnit) {
            actionUnitMapper.delete(actionUnitMap.get(l));
        }
    }

    private void updateKnowledgeSet(List<Long> newKnowledgeIds, List<Long> oldKnowledgeIds, Long robotId) {
        //更新每个组件中的知识库detail
        List<Long> addKnowledges = newKnowledgeIds.stream().filter(item -> !oldKnowledgeIds.contains(item)).collect(Collectors.toList());
        List<Long> removeKnowledges = oldKnowledgeIds.stream().filter(item -> !newKnowledgeIds.contains(item)).collect(Collectors.toList());

        //新增知识库
        for (Long addKnowledge : addKnowledges) {
            RobotKnowledge robotKnowledge = new RobotKnowledge();
            robotKnowledge.setRobotId(robotId);
            robotKnowledge.setKnowledgeId(addKnowledge);
            robotKnowledgeMapper.create(robotKnowledge);
        }

        //解绑知识库
        for (Long removeKnowledge : removeKnowledges) {
            robotKnowledgeMapper.deleteByRobotIdAndKnowledgeId(robotId, removeKnowledge);
        }


    }

    private void updateFileSet(List<ActionUnitDTO> fileSet, List<ActionUnit> actionUnits, Long robotId) {
        List<Long> oldIds = new ArrayList<>();//原本的文件夹列表
        for (ActionUnit actionUnit : actionUnits) {
            if (Objects.equals(actionUnit.getActionUnitType(), ActionUnitTypeEnum.DATA_SOURCE.getCode())) {
                //搜索组件只有一个，找到搜索组件的ID
                if (!(Objects.equals(actionUnit.getUnitTemplateCode(), "knowledge")
                        || Objects.equals(actionUnit.getUnitTemplateCode(), "website_url_parser"))) {
                    oldIds.add(actionUnit.getId());
                }
            }
        }

        Map<Long, ActionUnit> actionUnitMap = new HashMap<>();//根据ID查出对象，操作对应数据库
        for (ActionUnitDTO actionUnitDTO : fileSet) {
            ActionUnit actionUnit = new ActionUnit();
            BeanUtils.copyProperties(actionUnitDTO, actionUnit);
            actionUnit.setRobotId(robotId);
            actionUnit.setActionUnitType(ActionUnitTypeEnum.DATA_SOURCE.getCode());
            actionUnit.setDetail(actionUnitDTO.getDetail().toString());
            if (actionUnitDTO.getUnitId() == null) {
                actionUnit.setCreateTime(LocalDateTime.now());
                actionUnit.setUpdateTime(LocalDateTime.now());
                actionUnitMapper.create(actionUnit);
            } else {
                actionUnit.setId(Long.valueOf(actionUnitDTO.getUnitId()));
                actionUnitMap.put(actionUnit.getId(), actionUnit);
            }

        }

        List<String> newFileSet = fileSet.stream()
                .map(ActionUnitDTO::getUnitId)
                .collect(Collectors.toList());

        List<Long> newIds = newFileSet.stream()
                .map(str -> {
                    try {
                        // 尝试将字符串转换为Long
                        return Long.parseLong(str);
                    } catch (NumberFormatException e) {
                        // 如果转换失败，可以选择返回null或者抛出异常
                        // 这里我们选择返回-null
                        return null;
                    }
                })// 过滤掉null值
                .collect(Collectors.toList());


        List<Long> addFileSet = newIds.stream().filter(item -> !oldIds.contains(item)).collect(Collectors.toList());
        List<Long> removeFileSet = oldIds.stream().filter(item -> !newIds.contains(item)).collect(Collectors.toList());

        for (Long element : oldIds) {
            if (newIds.contains(element)) {
                //已有的更新
                ActionUnit actionUnitNeedUpdate = actionUnitMap.get(element);
                actionUnitNeedUpdate.setUpdateTime(LocalDateTime.now());
                actionUnitMapper.update(actionUnitNeedUpdate);
            }
        }
        //新增组件
//        for (Long addFileSetId : addFileSet) {
//            ActionUnit actionUnitNeedCreate = actionUnitMap.get(addFileSetId);
//            actionUnitNeedCreate.setCreateTime(LocalDateTime.now());
//            actionUnitNeedCreate.setUpdateTime(LocalDateTime.now());
//            actionUnitMapper.create(actionUnitNeedCreate);
//        }
        //解绑知识库and组件
        for (Long removeFileSetId : removeFileSet) {
//            ActionUnit actionUnitNeedDelete = actionUnitMap.get(removeFileSetId);
            ActionUnit removeActionUnit = actionUnitMapper.selectById(removeFileSetId);

            JSONObject detailJson = JSONObject.parseObject((String) removeActionUnit.getDetail());
            String fileSetId = (String) detailJson.get("fileSetId");
            knowledgeMapper.deleteById(fileSetId);

            actionUnitMapper.delete(removeActionUnit);
            //todo 删除文件，未通知算法
        }
    }

    private void updateBasicInfo(BasicInfoDTO basicInfo) {
        //更新basicInfo
        RobotRepoEntity robot = new RobotRepoEntity(basicInfo);
        robotRepository.updateBasic(robot);
    }

    /**
     * 新建机器人以及机器人-知识库
     *
     * @param robot
     * @return
     */
    @Autowired
    private ActionUnitImplKnowledge actionUnitImplKnowledge;

    @Autowired
    private ActionUnitImplBigModel actionUnitImplBigModel;
    @Autowired
    private ActionUnitImplWebSearch actionUnitImplWebSearch;

    @Transactional
    public RobotRepoEntity createRobotAndKnowledge(RobotRepoEntity robot) {
        // 创建智能体
        Long createNewID= robotRepository.create(robot);
        // 创建知识库ActionUnit
        actionUnitImplKnowledge.CreateThis(createNewID,robot.getRobotName(),robot.getUserId());
        return robot;
    }
    /**
     * 上传文件新建机器人以及机器人-知识库
     *
     * @param robot
     * @return
     */
    @Transactional
    public RobotRepoEntity createRobotAndKnowledgeByFiles(RobotRepoEntity robot, List<FileOverViewDTO> files) {
        robotRepository.create(robot);

        ActionUnit knowledgeActionUnit = new ActionUnit();
        knowledgeActionUnit.setActionUnitType(ActionUnitTypeEnum.DATA_SOURCE.getCode());
        knowledgeActionUnit.setUnitTemplateCode("knowledge");
        knowledgeActionUnit.setRobotId(robot.getId());
        knowledgeActionUnit.setUnitName(robot.getRobotName() + "知识库");
        String jsonString = JSONObject.toJSONString(new KnowledgeDetailVO());
        knowledgeActionUnit.setDetail(jsonString);
        knowledgeActionUnit.setCreateTime(LocalDateTime.now());
        knowledgeActionUnit.setUpdateTime(LocalDateTime.now());
        actionUnitMapper.create(knowledgeActionUnit);

        //创建默认知识库
        Knowledge knowledge = new Knowledge();
        knowledge.setKnowledgeType(KnowledgeTypeEnum.INDIVIDUAL.getCode());
        knowledge.setIsDelete(IsDeleteEnum.EXIST.getValue());
        knowledge.setKnowledgeName(robot.getRobotName() + "知识库");
        knowledge.setApplicationNumber(1);
        knowledge.setFileNumber(files.size());

        String bucketName = minioUtils.createBucket();
        knowledge.setMinioBucketName(bucketName);
        knowledgeMapper.create(knowledge);

        //创建批量上传文件夹
        Knowledge batchUploadSet = new Knowledge();
        batchUploadSet.setKnowledgeType(KnowledgeTypeEnum.BATCH_UPLOAD.getCode());
        batchUploadSet.setIsDelete(IsDeleteEnum.EXIST.getValue());
        batchUploadSet.setKnowledgeName(robot.getRobotName() + "批量上传文件夹");
        batchUploadSet.setApplicationNumber(0);
        batchUploadSet.setFileNumber(0);
        String batchUploadSetBucketName = minioUtils.createBucket();
        batchUploadSet.setMinioBucketName(batchUploadSetBucketName);
        knowledgeMapper.create(batchUploadSet);

        //文件上传新建机器人，将缓冲bucket的
        for (FileOverViewDTO file : files) {
            File newFile = new File();
            BeanUtils.copyProperties(file, newFile);
            newFile.setId(Long.valueOf(file.getFileId()));
            newFile.setMinioBucketName(bucketName);
            newFile.setKnowledgeId(knowledge.getId());

            String bufferFileName = file.getFileId() + "-" + file.getFileName();
            minioUtils.copyFile(BUFFER_BUCKET_NAME, bufferFileName, bucketName, bufferFileName);
            minioUtils.removeFile(BUFFER_BUCKET_NAME, bufferFileName);
            fileMapper.updateById(newFile);
//            fileMapper.update(newFile);
        }


        //创建机器人-知识库关系实体
        RobotKnowledge robotKnowledge = new RobotKnowledge();
        robotKnowledge.setKnowledgeId(knowledge.getId());
        robotKnowledge.setRobotId(robot.getId());
        robotKnowledgeMapper.create(robotKnowledge);

        //创建机器人-知识库关系实体
        RobotKnowledge batchUploadSetRobotKnowledge = new RobotKnowledge();
        batchUploadSetRobotKnowledge.setKnowledgeId(knowledge.getId());
        batchUploadSetRobotKnowledge.setRobotId(robot.getId());
        robotKnowledgeMapper.create(batchUploadSetRobotKnowledge);

        UserKnowledge userKnowledge = new UserKnowledge();
        userKnowledge.setKnowledgeId(knowledge.getId());
        userKnowledge.setUserId(robot.getUserId());
        userKnowledgeService.save(userKnowledge);

        UserKnowledge userKnowledgeBatchUploadSet = new UserKnowledge();
        userKnowledgeBatchUploadSet.setKnowledgeId(batchUploadSet.getId());
        userKnowledgeBatchUploadSet.setUserId(robot.getUserId());
        userKnowledgeService.save(userKnowledgeBatchUploadSet);

        return robot;
    }
    //  todo 未完成
    private void buildCreateRobotAlgorithmReqParam(){

    }


    /**
     * 一句话新建机器人
     *
     * @param createRobotDTO
     * @return
     */
    public AgentDetailVO createBySentence(CreateRobotDTO createRobotDTO) throws IOException {
        // 构造调用算法的参数
        List<Knowledge> knowledges = knowledgeMapper.queryByUserId(Long.valueOf(createRobotDTO.getUserId()));
        ArrayList<AgentCreate.Knowledge> knowledgeArrayList = new ArrayList<>();
        for (Knowledge knowledge : knowledges) {
            AgentCreate.Knowledge build = new AgentCreate.Knowledge().builder()
                    .id(knowledge.getId().toString())
                    .name(knowledge.getKnowledgeName()).build();
            knowledgeArrayList.add(build);
        }

        // 调用算法，补全一些机器人属性
        createRobotDTO.addSentenceByUseType(createRobotDTO.getCategoryName());
        CreateRobotResultDTO createRobotResultDTO = algorithmCaller.createBySentence(knowledgeArrayList, createRobotDTO.getSentence());
        RobotRepoEntity robot = new RobotRepoEntity();
        robot.FillFieldsByCreateRobotResultDTO(createRobotResultDTO);

        // 补全一些机器人属性
        robot.setCategoryName(createRobotDTO.getCategoryName());
        RequestContext.UserAccountInfoCtx userInfo= RequestContext.getUserAccountInfo();
        String componyCode = userInfo.getComponyCode();
        robot.setUserId(Long.valueOf(createRobotDTO.getUserId()));
        userInfo.getUserID();
        robot.setCompanyCode(componyCode);
        robot.setRobotUrl("https://picx.zhimg.com/70/v2-b1732f42c7a3d363565ca49c2de48739_1440w.avis?source=172ae18b&biz_tag=Post");// TODO 随机机器人头像 @张翔溪
        robot.setIsDelete(false);
        robot.setRobotScanPermissionType(RobotScanPermissionTypeEnum.INDIVIDUAL);
        robot.setCanEditType(CanEditTypeEnum.ONLY_CREATOR);
        robot.setRobotHeat(0);


        // 执行Mysql操作：创建机器人表记录，返回id；创建action_unit
        RobotRepoEntity newRobot = createRobotAndKnowledge(robot);

        // 执行Mysql操作：创建默认知识库组件
        Knowledge knowledge = new Knowledge();
        knowledge.setKnowledgeType(KnowledgeTypeEnum.INDIVIDUAL.getCode());
        knowledge.setIsDelete(IsDeleteEnum.EXIST.getValue());
        knowledge.setKnowledgeName(newRobot.getRobotName() + "知识库");
        knowledge.setApplicationNumber(1);
        knowledge.setFileNumber(0);
        String bucketName = minioUtils.createBucket();
        knowledge.setMinioBucketName(bucketName);
        knowledgeMapper.create(knowledge);

        // 执行mysql操作，绑定知识库
        for (String s : createRobotResultDTO.getKnowledgeList()) {
            RobotKnowledge robotKnowledge = new RobotKnowledge();
            robotKnowledge.setRobotId(newRobot.getId());
            robotKnowledge.setKnowledgeId(Long.valueOf(s));
            robotKnowledgeMapper.create(robotKnowledge);
        }

        if ("智能对话"==createRobotDTO.getFunction()){
            actionUnitImplBigModel.CreateThis(newRobot,ActionUnitTemplateCode.ai_big_model_text_chat);
        }else if ("图片绘制"==createRobotDTO.getFunction()){
            actionUnitImplBigModel.CreateThis(newRobot,ActionUnitTemplateCode.ai_big_model_make_picture);
        }else if("制作图表"==createRobotDTO.getFunction()){
            actionUnitImplBigModel.CreateThis(newRobot,ActionUnitTemplateCode.ai_big_model_make_echart);
        }else {
            //兜底，智能对话
            actionUnitImplBigModel.CreateThis(newRobot,ActionUnitTemplateCode.ai_big_model_text_chat);
        }

        actionUnitImplWebSearch.CreateThis(newRobot,ActionUnitTemplateCode.websearch_google);

        // 置顶
        robotUserUsetimeService.creatrobotuser(newRobot.getId().toString(),newRobot.getUserId().toString());
        // 返回创建的VO
        return queryRobotDetailByRobot(newRobot);
    }

    /**
     * 上传文件新建机器人
     *
     * @param createRobotDTO
     * @return
     */
    @Transactional
    public AgentDetailVO createByUploadFiles(CreateRobotDTO createRobotDTO) throws IOException {
        List<String> fileNames = new ArrayList<>();
        for (FileOverViewDTO file : createRobotDTO.getFiles()) {
            fileNames.add(file.getFileName());
        }
        //使用CreateRobotResultDTO接收返回结果
        CreateRobotResultDTO createRobotResultDTO = algorithmCaller.createByFiles(fileNames);
        //创建新机器人实体并写入默认数据与返回数据
        RobotRepoEntity robot = new RobotRepoEntity();
        BeanUtils.copyProperties(createRobotResultDTO, robot);
        robot.setUserId(Long.valueOf(createRobotDTO.getUserId()));

        RequestContext.UserAccountInfoCtx userInfo= RequestContext.getUserAccountInfo();
        // 公司ID
        String componyCode = userInfo.getComponyCode();
        robot.setCompanyCode(componyCode);
        robot.setRobotUrl("https://pan.cdwsnn.cloud/api/v3/file/get/13624/mmexport1727780972809.jpg?sign=3KANOeyRNq6jZ5BcaJW5u138V0IPRlimqJ_Pq9APdfg%3D%3A1727781680");// TODO 随机机器人头像 @李晨曦
        robot.setIsDelete(false);
        robot.setRobotScanPermissionType(RobotScanPermissionTypeEnum.INDIVIDUAL);
        robot.setCanEditType(CanEditTypeEnum.ONLY_CREATOR);
        robot.setCategoryName(createRobotDTO.getCategoryName());
        robot.setRobotHeat(0);

        //创建开场白JSON对象并赋给机器人实体
        Prologue prologue = new Prologue();
        prologue.setPrologueContent(createRobotResultDTO.getPrologue());
        prologue.setIsValid(true);
        prologue.setQuestionLead(createRobotResultDTO.getQuestionLead());
        robot.setPrologue(prologue);

        //新建后返回主键
        RobotRepoEntity newRobot = createRobotAndKnowledgeByFiles(robot, createRobotDTO.getFiles());
        // 置顶
        robotUserUsetimeService.creatrobotuser(newRobot.getId().toString(),newRobot.getUserId().toString());
        //创建返回的VO
        return queryRobotDetailByRobot(newRobot);
    }

    /**
     * // todo 串行改并行
     * 根据机器人实体查机器人详情
     *
     * @param robot
     * @return
     */
    public AgentDetailVO queryRobotDetailByRobot(RobotRepoEntity robot) {
        return queryRobotDetailByRobot(robot, true);
    }

    public AgentDetailVO queryRobotDetailByRobot(RobotRepoEntity robot, Boolean needActionUnitList) {
        AgentDetailVO agentDetailVO = new AgentDetailVO();
        Long robotId = robot.getId();

        //BASIC_INFO
        BasicInfoVO basicInfoVO = new BasicInfoVO();
        BeanUtils.copyProperties(robot, basicInfoVO);
//        PrologueVO prologueVO = assemblePrologue(robot.getPrologue().toString());
        basicInfoVO.setRobotId(String.valueOf(robot.getId()));
        basicInfoVO.setPrologue(robot.getPrologue());
        basicInfoVO.setRobotType(robot.getRobotScanPermissionType().getValue());

        agentDetailVO.setBasicInfo(basicInfoVO);
        basicInfoVO.setPrompt_template_info(robot.getPrompt_template_info());

        if (needActionUnitList) {
            //ACTION_UNIT
            List<ActionUnit> actionUnits = actionUnitMapper.selectByRobotId(robotId);
            List<DatasourceDetailVO> dataSource = new ArrayList<>();
            for (ActionUnit actionUnit : actionUnits) {
                if (actionUnit.getActionUnitType().equals(ActionUnitTypeEnum.DATA_SOURCE.getCode())) {
                    //DATASOURCE
                    DatasourceDetailVO datasourceDetail = datasourceDetail(actionUnit);
                    dataSource.add(datasourceDetail);
                } else if (actionUnit.getActionUnitType().equals(ActionUnitTypeEnum.BIG_MODEL.getCode())) {
                    //BIG_MODEL
                    BigModelVO bigModelDetail = bigModelDetail(actionUnit);
                    agentDetailVO.setBigModel(bigModelDetail);
                } else if (actionUnit.getActionUnitType().equals(ActionUnitTypeEnum.SEARCHING.getCode())) {
                    //SEARCHING
                    SearchingDetailVO searchingDetail = searchingDetail(actionUnit);
                    searchingDetail.setIsNeedWebSearching(robot.getIsNeedWebSearching());
                    agentDetailVO.setWebSearch(searchingDetail);
                }
            }

            agentDetailVO.setDatasource(dataSource);
        }

        return agentDetailVO;
    }

    private SearchingDetailVO searchingDetail(ActionUnit actionUnit) {
        ActionUnitOverViewVO actionUnitOverViewVO = copyActionUnitProperties(actionUnit);
        SearchingDetailVO searchingDetail = new SearchingDetailVO();
        searchingDetail.setActionUnit(actionUnitOverViewVO);
        searchingDetail.setActionUnitDetail((String) actionUnit.getDetail());
        return searchingDetail;
    }

    private BasicInfoVO getBasicInfo(RobotRepoEntity robot) {
        BasicInfoVO basicInfoVO = new BasicInfoVO();
        BeanUtils.copyProperties(robot, basicInfoVO);
//        PrologueVO prologueVO = assemblePrologue(robot.getPrologue().toString());
        basicInfoVO.setRobotId(String.valueOf(robot.getId()));
        basicInfoVO.setPrologue(robot.getPrologue());
        basicInfoVO.setPrompt_template_info(robot.getPrompt_template_info());
        return basicInfoVO;
    }



    private ActionUnitOverViewVO copyActionUnitProperties(ActionUnit actionUnit) {
        ActionUnitOverViewVO actionUnitOverViewVO = new ActionUnitOverViewVO();
        ActionUnitTemplate actionUnitTemplate = ActionUnitTemplateCache.cache.get(actionUnit.getUnitTemplateCode());
        actionUnitOverViewVO.setUnitTemplateName(actionUnitTemplate.getUnitTemplateName());
        actionUnitOverViewVO.setUnitId(String.valueOf(actionUnit.getId()));
        actionUnitOverViewVO.setUnitDesc(actionUnitTemplate.getUnitDesc());
        actionUnitOverViewVO.setUnitName(actionUnitTemplate.getUnitTemplateName());
        BeanUtils.copyProperties(actionUnit, actionUnitOverViewVO);
        return actionUnitOverViewVO;
    }

    /**
     * 获得大模型的detail
     *
     * @param actionUnit
     * @return
     */
    private BigModelVO bigModelDetail(ActionUnit actionUnit) {
        //设置基本action_unit信息
        BigModelVO bigModelVO = new BigModelVO();
        ActionUnitOverViewVO actionUnitOverViewVO = copyActionUnitProperties(actionUnit);
        bigModelVO.setActionUnit(actionUnitOverViewVO);

        if (actionUnit.getUnitTemplateCode().equals(ActionUnitTemplateCode.ai_big_model_make_echart.getValue())) {
            // 大模型绘表
            bigModelVO.setMakeEchartDetail(actionUnit.getDetail().toString());
            return bigModelVO;
        } else if (actionUnit.getUnitTemplateCode().equals(ActionUnitTemplateCode.ai_big_model_text_chat.getValue())) {
            // 大模型对话
            bigModelVO.setTextChatDetail(actionUnit.getDetail().toString());
            return bigModelVO;
        } else if (actionUnit.getUnitTemplateCode().equals(ActionUnitTemplateCode.ai_big_model_make_picture.getValue())) {
            // 图片绘制
            bigModelVO.setMakePictureDetail(actionUnit.getDetail().toString());
            return bigModelVO;
        } else if (actionUnit.getUnitTemplateCode().equals(ActionUnitTemplateCode.ai_big_model_robot.getValue())) {
            // 其他机器人
            JSONObject jsonObject = JSONObject.parseObject(actionUnit.getDetail().toString(), JSONObject.class);
            String robotId = jsonObject.getString("robotId");
            BasicInfoVO basicInfoVO = getBasicInfo(robotRepository.queryByRobotId(Long.valueOf(robotId)));
            bigModelVO.setRobotDetail(basicInfoVO);
            return bigModelVO;
        }
        return null;
    }


    public DatasourceDetailVO datasourceDetail(ActionUnit actionUnit) {
        ActionUnitOverViewVO actionUnitOverViewVO = copyActionUnitProperties(actionUnit);

        DatasourceDetailVO datasourceDetailVO = new DatasourceDetailVO();
        if (actionUnit.getUnitTemplateCode().equals("knowledge")) {
            KnowledgeDetailVO knowledgeDetail = knowledgeDetail(actionUnit);
            BeanUtils.copyProperties(knowledgeDetail, actionUnitOverViewVO);
            actionUnitOverViewVO.setDetail(knowledgeDetail.getActionUnit().getDetail());
            datasourceDetailVO.setActionUnit(actionUnitOverViewVO);
            return datasourceDetailVO;
        } else if (actionUnit.getUnitTemplateCode().equals("website_url_parser")) {
            WebParserDetailVO webParserDetailVO = new WebParserDetailVO();
            webParserDetailVO.setActionUnitDetail((String) actionUnit.getDetail());
            datasourceDetailVO.setActionUnit(actionUnitOverViewVO);
            datasourceDetailVO.setWebParserActionUnitDetail(webParserDetailVO);
            return datasourceDetailVO;
        } else {//文件解析
            FileParserOverViewVO fileParserDetail = fileParserDetail(actionUnit);
            actionUnitOverViewVO.setDetail(fileParserDetail);
            datasourceDetailVO.setActionUnit(actionUnitOverViewVO);
            return datasourceDetailVO;
        }
//        return datasourceDetailVO;
    }

    // region fileParserDetail----------------------------------方法
    private FileParserOverViewVO fileParserDetail(ActionUnit actionUnit) {
        JSONObject jsonObject = JSONObject.parseObject(actionUnit.getDetail().toString(), JSONObject.class);
        FileParserDetail fileParserDetail = new FileParserDetail();
        String fileSetId = jsonObject.getString("fileSetId");
        fileParserDetail.setFileSetId(fileSetId);

        List<String> supportFileTypeList = new ArrayList<>();
        Object jsonSupportFileTypeList = jsonObject.get("supportFileTypeList");
        String listStr = jsonSupportFileTypeList.toString();
        supportFileTypeList = JSONObject.parseArray(listStr, String.class);
        fileParserDetail.setSupportFileTypeList(supportFileTypeList);
        Knowledge knowledgeById = knowledgeMapper.queryByKnowledgeId(Long.parseLong(fileSetId));


        List<File> files = fileMapper.queryByKnowledgeId(Long.valueOf(fileParserDetail.getFileSetId()), 5L);
        List<FileOverViewVO> fileOverViewVOs = getAndUpdateFileUrl(files, Long.valueOf(fileParserDetail.getFileSetId()));
        fileParserDetail.setFileList(fileOverViewVOs);
        fileParserDetail.setKnowledgeName(knowledgeById.getKnowledgeName());

        //处理hasmore
        Knowledge fileset = knowledgeMapper.queryByKnowledgeId(Long.valueOf(fileParserDetail.getFileSetId()));
//        fileset.getKnowledgeName()
        if (fileset != null) {
            Integer fileNumber = fileset.getFileNumber();
            fileParserDetail.setHasMore(fileNumber > 5);
        } else {
            fileParserDetail.setHasMore(false);
        }
        FileParserOverViewVO fileParserOverViewVO = new FileParserOverViewVO();
        BeanUtils.copyProperties(fileParserDetail, fileParserOverViewVO);
        return fileParserOverViewVO;
    }
    // endregion fileParserDetail----------------------------------方法

    public KnowledgeDetailVO knowledgeDetail(ActionUnit actionUnit) {
        //根据机器人ID查询知识库
        KnowledgeDetailVO knowledgeDetailVO = new KnowledgeDetailVO();
        ActionUnitOverViewVO actionUnitOverViewVO = copyActionUnitProperties(actionUnit);
        knowledgeDetailVO.setActionUnit(actionUnitOverViewVO);

        List<Knowledge> knowledges = knowledgeMapper.queryKnowledgesByRobotId(actionUnit.getRobotId());
        List<KnowledgeOverViewVO> knowledgeOverViewVOs = new ArrayList<>();
        for (Knowledge knowledge : knowledges) {
            if (knowledge.getKnowledgeType() == 1 || knowledge.getKnowledgeType() == 2) {
                KnowledgeOverViewVO knowledgeOverViewVO = new KnowledgeOverViewVO();
                BeanUtils.copyProperties(knowledge, knowledgeOverViewVO);
                knowledgeOverViewVO.setKnowledgeId(String.valueOf(knowledge.getId()));
                knowledgeOverViewVOs.add(knowledgeOverViewVO);
            }
        }

        //查询每个知识库中的关联文件列表
        for (KnowledgeOverViewVO knowledgeOverViewVO : knowledgeOverViewVOs) {
            List<File> files = fileMapper.queryByKnowledgeId(Long.valueOf(knowledgeOverViewVO.getKnowledgeId()), 10L);
            List<FileOverViewVO> fileOverViewVOs = getAndUpdateFileUrl(files, Long.valueOf(knowledgeOverViewVO.getKnowledgeId()));
            knowledgeOverViewVO.setFileOverViewVOs(fileOverViewVOs);
        }
        knowledgeDetailVO.setActionUnitDetail(knowledgeOverViewVOs);
        return knowledgeDetailVO;
    }

    /**
     * 获取并且更新文件链接
     *
     * @param files
     * @param knowledgeId
     * @return
     */
    private List<FileOverViewVO> getAndUpdateFileUrl(List<File> files, Long knowledgeId) {
        List<FileOverViewVO> fileOverViewVOs = new ArrayList<>();
        for (File file : files) {
            LocalDateTime updateTime = file.getUpdateTime();
            long between = ChronoUnit.DAYS.between(updateTime, LocalDateTime.now());
            if (between >= 7) {//文件外链接过期,获取新链接
                String minioFileName = file.getId() + "-" + file.getFileName();
                String fileUrl = minioUtils.getPresignedObjectUrl(file.getMinioBucketName(), minioFileName);
                file.setFileUrl(fileUrl);
                fileMapper.update(file);
            }


            FileOverViewVO fileOverViewVO = new FileOverViewVO();

            BeanUtils.copyProperties(file, fileOverViewVO);
            fileOverViewVO.setFileId(String.valueOf(file.getId()));
            fileOverViewVO.setKnowledgeId(String.valueOf(knowledgeId));
            fileOverViewVOs.add(fileOverViewVO);

        }
        return fileOverViewVOs;
    }
}
